import styled from "@emotion/styled"
import { useEffect, useState, useRef } from "react"

const TimerWrapper = styled.div`
    display: inline-flex;
    gap: 4rem;
    color: #f50016;
    font-family: "Gilroy";
    font-weight: 500;
`

const TimeUnit = styled.span`
    font-size: 10rem;
    min-width: 20rem;
    text-align: center;
    background-color: #40444f;
    font-weight: 500;
    display: inline-block;
    height: 12rem;
    line-height: 12rem;
    border-radius: 2rem;
    color: #f9f9fa;
    font-family: "Roboto";
    min-width: 16rem;
`

const Separator = styled.span<{ blink?: boolean }>`
    font-size: 14rem;
    color: #40444f;
    font-weight: 700;
    display: inline-block;
    height: 12rem;
    line-height: 12rem;
    ${(props) =>
        props.blink &&
        `
        @keyframes blink {
            0% { color: #40444F; }
            50% { color: transparent; }
            100% { color: #40444F; }
        }
        animation: blink 1s steps(1) infinite;
    `}
`

interface CountdownTimerProps {
    totalSeconds?: number
    onTimeUp?: () => void
}

export default function CountdownTimer({
    totalSeconds = 72000, // 默认20小时
    onTimeUp,
}: CountdownTimerProps) {
    const [timeLeft, setTimeLeft] = useState(totalSeconds)
    const startTimeRef = useRef<number>(0)
    const frameRef = useRef<number>(0)

    useEffect(() => {
        if (timeLeft <= 0) {
            onTimeUp?.()
            return
        }

        const animate = (currentTime: number) => {
            if (!startTimeRef.current) {
                startTimeRef.current = currentTime
            }

            const elapsedTime = Math.floor((currentTime - startTimeRef.current) / 1000)
            const newTimeLeft = totalSeconds - elapsedTime

            if (newTimeLeft <= 0) {
                setTimeLeft(0)
                onTimeUp?.()
                return
            }

            setTimeLeft(newTimeLeft)
            frameRef.current = requestAnimationFrame(animate)
        }

        frameRef.current = requestAnimationFrame(animate)

        return () => {
            if (frameRef.current) {
                cancelAnimationFrame(frameRef.current)
            }
        }
    }, [totalSeconds, onTimeUp, timeLeft])

    // 将秒数转换为时分秒
    const hours = Math.floor(timeLeft / 3600)
    const minutes = Math.floor((timeLeft % 3600) / 60)
    const seconds = timeLeft % 60

    const formatNumber = (num: number) => String(num).padStart(2, "0")

    return (
        <TimerWrapper>
            <TimeUnit>{formatNumber(hours)}</TimeUnit>
            <Separator>:</Separator>
            <TimeUnit>{formatNumber(minutes)}</TimeUnit>
            <Separator blink>:</Separator>
            <TimeUnit>{formatNumber(seconds)}</TimeUnit>
        </TimerWrapper>
    )
}
